<template>
    <div>
        <x-button class="btn-file" size="small">选择文件
            <input type="file" multiple class="inputfile" @change="choseFiles($event,onlyImg)">
        </x-button>
        <!-- <input type="file" multiple class="inputfile" @change="choseFiles($event,onlyImg)"> -->
        <div class="tiptxt">{{tips}}</div>
        <x-button v-if="canUploadAll" class="upload-all" @click.native="uploadAll">全部上传</x-button>
        <div v-if="fileList.length>0" class="fileListArea">
            <ul width="100%">
                <li v-for="(f,i) in fileList" :key="i">
                    <div class="l">
                        <span class="img" v-if="f.url" :style="'background-image:url(' +f.url+')'"></span>
                        <span class="name" v-else>{{f.name}}</span>
                    </div>
                    <div class="m">
                        <span class="sss default" v-if="f.status==1">待上传</span>
                        <span class="sss success" v-if="f.status==3">上传成功</span>
                        <span class="sss danger" v-if="f.status==4">上传失败</span>
                    </div>
                    <div class="r">
                        <span class="aaa" @click="remove(f.id)">移除</span>
                    </div>
                </li>
            </ul>
        </div>
    </div>
</template>
<script>
//vux
import { XButton } from 'vux';
//七牛
import { getUpToken } from '@/api/qn';
export default {
    data() {
        return {
            canUploadAll: false,
            eid: this.$route.query.eid,
            qnData: { upData: { key: '', token: '' }, uploadHost: '' },
            finalUploadFiles: [],
            fileList: this.orignFileList,
        }

    },
    components: {
        XButton,
    },

    props: ['onlyImg', 'tips', 'field', 'orignFileList', "subIndex", "subField"],
    watch: {
        // 监听外部对props属性orignFileList的变更，并同步到组件内的data属性fileList中
        orignFileList(val) {
            if (!val || val.length == 0) {
                this.fileList = [];
                this.finalUploadFiles = [];
            } else if (!this.fileList || this.fileList.length == 0) {
                this.fileList = val;
            }
        },
    },
    methods: {
        /**
         * 上传文件至七牛
         */
        doUpload(upingFile, fileData) {
            upingFile.status = 2
            let f = fileData.file
            let key = fileData.id + '_' + f.name
            var xhr = new XMLHttpRequest();
            xhr.open('POST', this.qnData.uploadHost, true);
            var formData = new FormData();
            formData.append('key', key);
            formData.append('token', this.qnData.upData.token);
            formData.append('file', f);
            xhr.onreadystatechange = (response) => {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        upingFile.status = 3
                        upingFile.url = this.qnData.showHost + "/" + key
                        this.removeFromUploadQueue(fileData.id)
                        this.canUploadAll = false
                        this.$emit('callBack', this.field, this.fileList, this.subIndex, this.subField, this.canUploadAll)
                    } else if (xhr.status == 401) {
                        this.doUpload(f);
                    } else {
                        upingFile.status = 4
                        this.canUploadAll = true;
                        this.removeFromUploadQueue(fileData.id)
                        this.$emit('callBack', this.field, this.fileList, this.subIndex, this.subField, this.canUploadAll, this.canUploadAll)
                        console.log('意外错误:code:' + xhr.status + ',resp:' + xhr.responseText);
                    }
                }
            };
            // ============进度条=========
            // 开始时间
            let start = +new Date()
            // 已上传文件大小
            let uploadedSize = 0
            xhr.upload.onprogress = (evt) => {

                // event.total是需要传输的总字节，event.loaded是已经传输的字节。如果event.lengthComputable不为真，则event.total等于0
                if (evt.lengthComputable) {
                    upingFile.percent = Math.round(evt.loaded / evt.total * 100);
                }

                var time = document.getElementById("time");
                var pertime = (+new Date() - start) / 1000; //计算出上次调用该方法时到现在的时间差，单位为s
                start = +new Date(); //重新赋值时间，用于下次计算

                var perload = evt.loaded - uploadedSize; //计算该分段上传的文件大小，单位kb       
                uploadedSize = evt.loaded;//重新赋值已上传文件大小，用以下次计算

                //上传速度计算
                var speed = perload / pertime;//单位b/s
                var bspeed = speed;
                var units = 'b/s';//单位名称
                if (speed / 1024 > 1) {
                    speed = speed / 1024;
                    units = 'Kb/s';
                }
                if (speed / 1024 > 1) {
                    speed = speed / 1024;
                    units = 'Mb/s';
                }
                speed = speed.toFixed(1);
                //预计剩余时间
                var restTime = parseInt((evt.total - evt.loaded) / bspeed);
                console.log(upingFile.name + '，速度：' + speed + units + '，预计剩余时间：' + restTime + 's')
            }
            xhr.send(formData);
        },
        /**
        * 多文件上传
        */
        choseFiles(event, onlyImg, ctx) {
            if (event.target.files.length > 0) {
                let files = event.target.files
                let upFiles = []
                for (let i = 0; i < files.length; i++) {
                    const file = files[i];
                    let size = file.size / 1024 < 1024 ? (file.size / 1024).toFixed(2) + 'KB' : (file.size / 1024 / 1024).toFixed(2) + 'MB'
                    let suffix = '.' + file.name.replace(/.+\./, "")
                    let isPic = file.type ? file.type.indexOf('image') > -1 : false;
                    if (onlyImg && !isPic) {
                        // 如果只能上传图片
                        this.$message.error('只能上传图片')
                        return
                    }
                    let id = +new Date() + '_' + i
                    upFiles.push({
                        id: id,
                        name: file.name,
                        size: size,
                        suffix: suffix,
                        url: null,
                        status: 1,//待上传
                        percent: 0,
                    })
                    this.finalUploadFiles.push({ id: id, file: file })
                }
                this.fileList = this.fileList.concat(upFiles)
                this.canUploadAll = true
                this.$emit('callBack2', this.canUploadAll)
            } else {
                this.canUploadAll = false
            }

        },
        /**
         * 上传全部文件
         */
        async uploadAll() {
            if (!this.qnData.uploadHost) {
                //获取七牛上传token
                await getUpToken(this.eid).then((resp) => {
                    this.qnData.uploadHost = resp.uploadHost
                    this.qnData.showHost = resp.showHost
                    this.qnData.upData.token = resp.token
                }).catch(_ => {
                    this.$message.error('获取七牛上传参数失败')
                })
            }
            if (this.qnData.uploadHost) {
                this.canUploadAll = false
                this.finalUploadFiles.forEach(fitem => {
                    let upingFile = this.fileList.filter(item => item.id == fitem.id)[0]
                    console.log(upingFile, fitem)
                    this.doUpload(upingFile, fitem)
                })
            }
        },
        /**
         * 移除文件
         */
        remove(id) {
            this.fileList = this.fileList.filter(item => item.id != id)
            this.finalUploadFiles = this.finalUploadFiles.filter(item => item.id != id)
            this.$emit('callBack', this.field, this.fileList, this.subIndex, this.subField)
            if (this.finalUploadFiles.length == 0) {
                this.canUploadAll = false;
            }
        },
        /**
         * 从上传队列中移除文件
         */
        removeFromUploadQueue(id) {
            this.finalUploadFiles = this.finalUploadFiles.filter(item => item.id != id)
        }
    },
}
</script>

<style lang="scss">
.cl-group button {
  font-size: 0.56rem !important;
  display: inline-block;
  width: auto !important;
  margin-left: 0;
  border: 1px solid rgba(0, 0, 0, 0.2) !important;
  line-height: 1.4rem !important;
  &:after {
    border: 0;
  }
}
.btn-file {
  position: relative;
  .inputfile {
    height: 28px;
    width: 56px;
    opacity: 0;
    position: absolute;
    z-index: 10;
    left: 0;
    top: 0;
  }
}

.upload-all {
  float: right;
  border: 1px solid rgba(126, 6, 6, 0.2) !important;
  background-color: #fa5555 !important;
  color: #fff !important;
}

.tiptxt {
  display: inline-block;
  margin-top: 0;
  margin-left: 20px;
  color: #a6a8ad;
}

.sss {
  // margin-top: 4px;
  display: inline-block;
  background-color: rgba(64, 158, 255, 0.1);
  padding: 0 10px;
  line-height: 1.2rem;
  font-size: 12px;
  color: #409eff;
  border-radius: 4px;
  box-sizing: border-box;
  border: 1px solid rgba(64, 158, 255, 0.2);
}
.aaa {
  color: #409eff;
}
.sss.success {
  background-color: rgba(103, 194, 58, 0.1);
  border-color: rgba(103, 194, 58, 0.2);
  color: #67c23a;
}
.progress_f {
  display: flex;
  margin-bottom: 1vh;
}
#progressBar {
  flex: 1;
}
progress::-webkit-progress-value,
progress::-moz-progress-bar {
  background: orange;
}
</style>
